package com.vincent.exam.tree;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class RebuildTree {

    public static void main(String[] args) {
        //[1,2,4,5,6,3],[5,4,6,2,1,3]
        int[] pre = new int[]{1,2,4,5,6,3};
        int[] mid = new int[]{5,4,6,2,1,3};
        int[] solve = new RebuildTree().solve(pre, mid);
        for (int i : solve) {
            System.out.println(i);
        }
    }
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     * 求二叉树的右视图
     * @param xianxu int整型一维数组 先序遍历
     * @param zhongxu int整型一维数组 中序遍历
     * @return int整型一维数组
     */
    public int[] solve (int[] xianxu, int[] zhongxu) {
        TreeNode root = rebuild(xianxu, zhongxu);
        bfs(root, 0);
        int[] result = new int[list.size()];
        int i=0;
        for (List<Integer> levelNodes : list) {
            int last = 0;
            for (Integer nodeVal : levelNodes) {
                last = nodeVal;
            }
            result[i] = last;
            i++;
        }
        return result;
    }


    /**
     * 利用前序，中序结果进行重建树结构
     * @param pre
     * @param mid
     * @return
     */
    public TreeNode rebuild(int[] pre, int[] mid) {
        if (pre == null || mid == null || pre.length==0 || mid.length==0) {
            return null;
        }
        // 根节点的值为前序的第一个元素
        int val = pre[0];
        int pos = 0;
        for (int i = 0; i < mid.length; i++) {
            if (mid[i] == val) {
                pos = i;
            }
        }
        TreeNode root = new TreeNode(val);
        // 中序遍历到pos之前的节点都是左子树的结，由此可以拿到前序（第一个节点为根）的左子树的遍历结果为[1,pos+1) 中序为[0,pos)
        root.left = rebuild(Arrays.copyOfRange(pre, 1, pos + 1), Arrays.copyOfRange(mid, 0, pos));
        root.right = rebuild(Arrays.copyOfRange(pre, pos + 1, pre.length), Arrays.copyOfRange(mid, pos + 1, mid.length));
        return root;
    }

    private List<List<Integer>> list = new ArrayList<>();

    /**
     * 层序遍历
     * @param treeNode
     * @param level
     */
    public void bfs(TreeNode treeNode, int level){
        if (list.size() == level){
            list.add(new ArrayList<Integer>());
        }
        List<Integer> levelNodes = list.get(level);
        levelNodes.add(treeNode.val);
        if (treeNode.left != null){
            bfs(treeNode.left, level+1);
        }
        if (treeNode.right != null){
            bfs(treeNode.right, level + 1);
        }
    }
}
